<?php
class ProjectActController extends Zone_Action{
	public function indexAction(){
		$this->removeLayout();
		$user_id = get_user_id();
		$act = get('act',NULL);
		
		switch( $act ){
			case "unread":
				$this->unRead();
				break;
			case "read":
				$this->setRead();
				break;
		}	
	}

	protected function unRead(){
		$user_id = get_user_id();
		$ids = get('ID',array(),true);
		
		if( count($ids) > 0 ){
			foreach( $ids as $j => $v ){
				$ids[$j] = "'$v'";
			}
			$this->Model->delete("projects_reads","`project_id` IN (".implode(',',$ids).") AND `user_id`='$user_id'");	

			if( get('back','') != 'yes' ){	
				$this->setJSON(array(
					reload	=> 'yes'
				));
			}else{
				$this->setJSON(array(
					redirect => '#Project'
				));
			}			
		}else{
			return $this->setJSON(array(
				alert	=> "Chưa chọn công việc nào"
			));
		}		
	}
	
	protected function setRead(){
		$user_id = get_user_id();
		$ids = get('ID',array(),true);

		if( count($ids) == 0 ){
			return $this->setJSON(array(
				alert	=> "Chưa chọn công việc nào"
			));
		}	
		
		foreach( $ids as $j ){
			$check = $this->Model->fetchRow("SELECT `a`.`ID`
				FROM  `projects` as `a`
				LEFT JOIN `projects_users` as `b`
					ON `b`.`user_id`='$user_id' AND `b`.`project_id`=`a`.`ID`
				WHERE `a`.`is_draft`='no' AND ( `b`.`user_id` IS NOT NULL OR `a`.`created_by_id`='$user_id' ) AND `a`.`ID`='$j'");
			
			if( $check ){
				if( !$this->Model->fetchRow("SELECT * FROM `projects_reads` WHERE `project_id`='$j' AND `user_id`='$user_id'") ){
					$this->Model->insert('projects_reads',array(
						project_id	=> $j,
						user_id		=> $user_id,
						date_read	=> mysql_date()
					));
				}	
			}
		}
		$this->setJSON(array(
			reload	=> 'yes'
		));
	}
}	